using System;
using System.Collections.Generic;
using System.Text;

namespace Walkmen.Util
{
    public sealed class NumericUtils
    {
        private NumericUtils()
        {
        }

        public static short ReadShort(byte[] buffer, int offset)
        {
            return (short)((buffer[offset + 0] << 8) + buffer[offset + 1]);
        }

        public static byte[] WriteShort(short value)
        {
            byte[] result = new byte[2];
            result[0] = (byte)((value & 0xFF00) >> 8);
            result[1] = (byte)((value & 0x00FF));

            return result;
        }

        public static int ReadInt24(byte[] buffer, int offset)
        {
            return (buffer[offset + 0] << 16) + (buffer[offset + 1] << 8) + (buffer[offset + 2]);
        }

        public static int ReadInt32(byte[] buffer, int offset)
        {
            return (buffer[offset + 0] << 24) + (buffer[offset + 1] << 16) + (buffer[offset + 2] << 8) + (buffer[offset + 3]);
        }

        public static byte[] WriteInt32(int value)
        {
            byte[] result = new byte[4];
            result[0] = (byte)((value & 0xFF000000) >> 24);
            result[1] = (byte)((value & 0x00FF0000) >> 16);
            result[2] = (byte)((value & 0x0000FF00) >> 8);
            result[3] = (byte)((value & 0x000000FF));

            return result;
        }

        public static int ReadSynchsafeInt32(byte[] buffer, int offset)
        {
            return ((buffer[offset + 0] & 0x7F) << 21) | ((buffer[offset + 1] & 0x7F) << 14) | ((buffer[offset + 2] & 0x7F) << 7) | (buffer[offset + 3] & 0x7f);
        }

        public static byte[] WriteSynchsafeInt32(int value)
        {
            byte[] result = new byte[4];
            result[0] = (byte)((value & 0xFE00000) >> 21);
            result[1] = (byte)((value & 0x01FC000) >> 14);
            result[2] = (byte)((value & 0x0003F80) >> 7);
            result[3] = (byte)((value & 0x000007F));

            return result;
        }
    }
}
